package com.jprocms.module.cms.exception.handler;

import com.jpro.framework.common.util.collection.SetUtils;
import com.jpro.module.infra.api.logger.ApiErrorLogApi;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.exception.PortalServiceException;
import com.jprocms.module.cms.util.CmsContextUtil;
import com.jprocms.module.cms.util.FrontContextUtil;
import com.jprocms.module.cms.util.RequestUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * CMS异常处理器，将 Exception 翻译成 CommonResult + 对应的异常编号
 *
 * @author jprocms
 */
@ControllerAdvice
@AllArgsConstructor
@Slf4j
public class CmsExceptionHandler {

    /**
     * 忽略的 ServiceException 错误提示，避免打印过多 logger
     */
    public static final Set<String> IGNORE_ERROR_MESSAGES = SetUtils.asSet("无效的刷新令牌");

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    private final String applicationName;

    private final ApiErrorLogApi apiErrorLogApi;

    /**
     * 处理业务异常 ServiceException
     * <p>
     * 例如说，站点关闭
     */
    @ExceptionHandler(value = PortalServiceException.class)
    public String serviceExceptionHandler(PortalServiceException ex) {
        log.warn("[PortalServiceException] tpl:{} message:{}", ex.getTpl(), ex.getMessage());
        final SiteDO site = CmsContextUtil.getSite();
        final HttpServletRequest request = RequestUtils.getHttpServletRequest();
        request.setAttribute("message", ex.getMessage());
        FrontContextUtil.setData(request);
        return site.joinTemplate(ex.getTpl());
    }

}
